//
//  ST_DTChatMessage.swift
//  mewpoo
//
//  Created by DouLei on 2018/9/28.
//  Copyright © 2018 DouLei. All rights reserved.
//


import UIKit
import SnapKit
import SwiftyUserDefaults
import RealmSwift
import SwifterSwift
import MJRefresh
import SwiftyJSON
import NIMSDK
import SwiftyAttributes


enum ST_DTChatCellStyle{
    case Text,Image,Video,voice,timeinterval,recall,gif,goodsType,CustomNewEmoji,redPacket,redPacketReceived,likeProp,incomeGuard,incomeGift,snapChat,recharge,tips,unlockCallTips,callRecord,inviteVoiceGroup,femaleInviteChat
    
    
    /**
     需要扣费的消息类型
     */
    static let ingredients: Set<ST_DTChatCellStyle> = [.Text,.Image,.voice,.Video,.snapChat,.CustomNewEmoji]
  
}

enum ST_DTChatCellDirection {
    case send,receive
}

enum ST_DTChatUploadStatus {
    case uploading,success,failure
}


enum ST_DTChatRedPacketStatus:Int {
    case normal = 0,received,expire
}

var ST_ChatRightBackImage:UIImage = {
    return UIImage.init(color: Color.init(hex: 0xFEC207)!, size: CGSize.init(width: 1, height: 1))
}()

var ST_ChatLeftBackImage:UIImage = {
    return UIImage.init(color: Color.init(hex: 0xF2F4F7)!, size: CGSize.init(width: 1, height: 1))
}()

class ST_DTChatMessage:NSObject{
    
    
    ///云信消息ID
    private var localNIM_ID = ""
    /// 本地标识
    private let localUUID = UUID().uuidString
    
    /// 消息唯一ID
    fileprivate(set) var uuid:String{
        get{
            if localNIM_ID.count > 0{
                return localNIM_ID
            }else{
                return localUUID
            }
        }set{
            self.localNIM_ID = newValue
        }
    }
    /// 直接发送ST_DTChatMessage时，创建NIMMessage 同时self.uuid = 云信消息ID
    func create_send_n_i_m_message()->NIMMessage{
        
        let msg = NIMMessage()
        
        self.uuid = msg.messageId
        
        return msg
    }
    
    var remoteExt = [String:Any]()
//    var userID:String!
    
    var uploadImageProgress:Int32 = 0
    
    var uploadStatus:ST_DTChatUploadStatus = .uploading
    /**秒*/
    var messageTime:Int64 = 0
    var cellStyle:ST_DTChatCellStyle = .Text
    /// 消息的方向
    var direction:ST_DTChatCellDirection?
    
    /**
     点赞特质消息
     */
    var displayThumbUp = false
//    间隙
    var timeintervalStr = ""
//    撤回
    var recallStr = ""
    //    MARK:- data
    var chatID = ""
    
    var userName = ""
//    -----------图片
    var chatImageSize = CGSize.zero
    
//    本地
    var thumbnailImageLocalPath:String?
    
    var imageLocalURL:String?
//    远程
    var thumbnailImageRemoteUrl:String?
    
    var imageRemoteUrl:String?
    
//    被销毁
    var isSnapDestroy = false
    ///通过鉴定的消息
    var passedCheck:Bool?
    
//    -----语音
//    本地
    var voiceLocalPath:String?
//    远程
    var voiceRemoteUrl:String?
//    秒为单位
    var voiceDuration:Int = 0
    
    var audioPlaying = false
    //    文字
    var chatText:String = ""
    var portraitUri:String = ""
    
//    表情
    var expPosition = 0
//    dynamic表情
    var emojiURL = ""
//    表情个数
    var emojiCount = 1
//    ------视频
//    本地视频路径
    var videoLocalPath = ""
//    本地缩略图
    var videoThumbnailPath = ""
    
    var videoWidth = 0.cgFloat
    
    var videoHeight = 0.cgFloat
    ///远程
    var videoThumbnailImageUrl = ""
    ///远程
    var videoUrl = ""
//    ----- 商品
    var goods:ST_BTIMGiftMessageModel?
    /// 邀请语音房
    var inviteVoiceRoom:ST_BTIMInviteMessageModel?
    
    /// 女性邀请通话 类型 1 语音  2视频
    var femaleInviteChatType:Int?
//     ----- 通话记录
    var callRecord:ST_Tian270AttachmentModel?
    
//    ----- custom提示
    var customTips:ST_Custom264AttachmentModel?
    
    lazy var littleLuckTips:NSAttributedString = {
        
        let normalAttr:[Attribute] = [.font(UIFont.systemFont(ofSize: 14)),.textColor(UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1))]
        
        let yellowAttr:[Attribute] = [.font(UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)),.textColor(UIColor.init(hex: 0xFEC207)!)]
        
        
        let attrString = "恭喜！你们的亲密度达到".withAttributes(normalAttr)
        
        let str0 = "小幸运".withAttributes(yellowAttr)
        let str1 = "啦！现在可以使用语音、视频通话功能了哦！趁着聊得火热，立刻拨通加深了解吧！".withAttributes(normalAttr)
      
        
        attrString.append(str0)
        attrString.append(str1)
        
        attrString.addAttributes([NSAttributedString.Key.paragraphStyle:NSParagraphStyle.create_line_spacing_paragraph_style(lineSpacing: 2)], range: NSRange(location: 0, length: attrString.length))
        
        return attrString
    }()
//    ------ Emoji
    var emoji:ST_BTIMEmojiMessageModel?
    
//    ---- 255版本自定义消息
    var customAttachment255:ST_Custom255AttachmentModel?
    
    var redPacketStatus = ST_DTChatRedPacketStatus.normal
    
    //MARK: - gif
    var gifWidth = 0.cgFloat
    
    var gifHeight = 0.cgFloat
    /*gif封面*/
    var gifCoverImg :UIImage?
    //原图
    var gifImg :UIImage?
    /*gif原图*/
    var gifData :Data?

    //    省略图的url
    var gifThumbnailImageUrl = ""
    //    gif的url
    var gifUrl = ""

    var tail = ST_ChatMessageTailControlModel()
    
    /// 礼物数量展示
    var giftNumberAttributeString:NSAttributedString?
    //    MARK:- frame
    private let marginTop:CGFloat = 15.0
    
    private let marginRight:CGFloat = 30.0
    
    var cellHeight:CGFloat = 0.0
    
    var iconFrame:CGRect = CGRect.zero
    
    var errorStatusGap:CGFloat = 10
    
    var errorStatusFrame:CGRect = CGRect.zero
    
    var audioFrame:CGRect = CGRect.zero
    
    var audioWidth:CGFloat = 30.cgFloat
    
    var imageFrame:CGRect = CGRect.zero
    
    var textBackFrame:CGRect = CGRect.zero
    
    var textBackImage:UIImage!
    
    var textFrame:CGRect = CGRect.zero
//    表情
    var localEmojiImageFrame:CGRect = CGRect.zero
    //    表情个数
    var localEmojiCountFrame:CGRect = CGRect.zero
    
    func updateFrom(locExt:JSON){
        
        //        阅后即焚
        if let isSnapDestroy = locExt["isSnapDestroy"].bool{
            self.isSnapDestroy = isSnapDestroy
        }
        
        //        通过数美检测
        if let passed = locExt["passedCheck"].bool{
            self.passedCheck = passed
        }
        
        
        
    }
    
    
    func figureFrame(){
        
        if let direction = direction{
        
            if direction == .receive{
                
                iconFrame = CGRect.init(x: marginTop, y: marginTop, width: DTChatUserImageWidth, height: DTChatUserImageWidth)
                
            }else{
                
                iconFrame = CGRect.init(x: ScreenWidth, y: marginTop, width: 0, height: 0)
            }
            
        }else{
            
            iconFrame = .zero
        }
        
        
        
        if cellStyle == .Text{
            
            let size = chatText.size(withConstraintRect: CGSize.init(width: DTChatTextWidthMax, height: .greatestFiniteMagnitude), font: DTChatTextFont)
            
//            if size.width < (size.height + 3){
//                size = CGSize.init(width: size.height + 3, height: size.height)
//            }
            
            let textMargin:CGFloat = 10
            
            let backHeight = size.height + textMargin * 2
            
            var backWidth = size.width + textMargin * 2
            
            if backHeight > backWidth && backHeight < 100{
                backWidth = backHeight
            }
            
            let backSize = CGSize.init(width: backWidth, height: backHeight)
            
            if direction == .receive{
                
//                textBackFrame = CGRect.init(x: iconFrame.maxX+marginTop, y: iconFrame.origin.y, width: size.width + textMargin * 2, height: size.height + textMargin * 2)
                
                let backOrigin = CGPoint.init(x: iconFrame.maxX+marginTop, y: iconFrame.origin.y)
                
                textBackFrame = CGRect.init(origin: backOrigin, size: backSize)
                
                let textOrigin = (backSize.width - size.width)/2.0
                
                textFrame = CGRect.init(origin: CGPoint.init(x: textOrigin, y: textMargin), size: size)
                
                textBackImage = ST_ChatLeftBackImage
                
                let errorY = textBackFrame.origin.y + (textBackFrame.height - ST_DTChatCell.uploadErrorBtnSize.height)/2.0
                
                errorStatusFrame = CGRect.init(origin: CGPoint.init(x: textBackFrame.maxX + errorStatusGap, y: errorY), size: ST_DTChatCell.uploadErrorBtnSize)
                
                cellHeight = textBackFrame.maxY + marginTop
                
                if self.tail.status != .hidden{
                    cellHeight += 17+5
                }
                
            }else{
                
                let backOrigin = CGPoint.init(x: ScreenWidth - backSize.width - marginRight, y: iconFrame.origin.y)
                
                textBackFrame = CGRect.init(origin: backOrigin, size: backSize)
                
                let textOrigin = (backSize.width - size.width)/2.0
                
                textFrame = CGRect.init(origin: CGPoint.init(x: textOrigin, y: textMargin), size: size)
                
                textBackImage = ST_ChatRightBackImage
                
                let errorY = textBackFrame.origin.y + (textBackFrame.height - ST_DTChatCell.uploadErrorBtnSize.height)/2.0
                
                errorStatusFrame = CGRect.init(origin: CGPoint.init(x: textBackFrame.origin.x - errorStatusGap - ST_DTChatCell.uploadErrorBtnSize.width , y: errorY), size: ST_DTChatCell.uploadErrorBtnSize)
            
                
                cellHeight = textBackFrame.maxY + marginTop
            }
            
            
        }
        if cellStyle == .Image{
            
            var imageWidth:CGFloat = 0
            var imageHeight:CGFloat = 0
            var displayImageWidth:CGFloat = 0
            var displayImageHeight:CGFloat = 0
       
            imageWidth = chatImageSize.width
            imageHeight = chatImageSize.height
                //                宽图
                if imageWidth > imageHeight{
                    
                    displayImageWidth = 140
                    
                    displayImageHeight = 140/imageWidth*imageHeight
                }
                    //                长图
                else if  imageWidth < imageHeight{
                    
                    displayImageHeight = 140
                    
                    displayImageWidth = 140/imageHeight*imageWidth
                    
                }else{
                    displayImageHeight = 140
                    displayImageWidth = 140
                }
//                左边
                if direction == .receive{
                    imageFrame = CGRect.init(origin: CGPoint.init(x: iconFrame.maxX + 10, y: iconFrame.origin.y), size: CGSize.init(width: displayImageWidth, height: displayImageHeight))
                }else{
                    imageFrame = CGRect.init(x:  iconFrame.origin.x - marginRight - displayImageWidth, y: iconFrame.origin.y, width: displayImageWidth, height: displayImageHeight)
                }
                
                cellHeight = imageFrame.maxY + marginTop
            
                if self.tail.status != .hidden{
                    cellHeight += 17+5
                }
        }
        
        if cellStyle == .voice {
            
            self.audioWidth = 70 + CGFloat(150/60.0)*CGFloat(voiceDuration)
        
            
            var x:CGFloat = 0
            if direction == .send{
                x = iconFrame.origin.x - marginRight - audioWidth
            }else{
                x = iconFrame.maxX + 10
            }
            audioFrame = CGRect.init(x: x, y: iconFrame.origin.y, width: self.audioWidth, height: 44)
            
            
            cellHeight = iconFrame.origin.y + 44 + marginTop
            
            if self.tail.status != .hidden{
                cellHeight += 17+5
            }
            
        }
        
        if cellStyle == .timeinterval || cellStyle == .recall {
            cellHeight = 50
        }
        
        
        if cellStyle == .gif{
            
            let imageWidth:CGFloat = self.gifWidth
            let imageHeight:CGFloat = self.gifHeight
            
            var displayImageWidth:CGFloat = 0
            var displayImageHeight:CGFloat = 0
            //                宽图
            if imageWidth > imageHeight{
                
                displayImageWidth = 140
                displayImageHeight = 140/imageWidth*imageHeight
            
            }else if  imageWidth < imageHeight{                //                长图

                displayImageHeight = 140
                displayImageWidth = 140/imageHeight*imageWidth
                
            }else{
                displayImageHeight = 140
                displayImageWidth = 140
            }
            
            if direction == .receive{
                
                imageFrame = CGRect.init(origin: CGPoint.init(x: iconFrame.maxX + 10, y: iconFrame.origin.y), size: CGSize.init(width: displayImageWidth, height: displayImageHeight))
                
                let errorY = imageFrame.origin.y + (imageFrame.height - ST_DTChatCell.uploadErrorBtnSize.height)/2.0
                
                errorStatusFrame = CGRect.init(origin: CGPoint.init(x: imageFrame.maxX + errorStatusGap, y: errorY), size: ST_DTChatCell.uploadErrorBtnSize)
                
            }else{
                
                imageFrame = CGRect.init(x:  iconFrame.origin.x - marginRight - displayImageWidth, y: iconFrame.origin.y, width: displayImageWidth, height: displayImageHeight)
                
                let errorY = imageFrame.origin.y + (imageFrame.height - ST_DTChatCell.uploadErrorBtnSize.height)/2.0
                
                errorStatusFrame = CGRect.init(origin: CGPoint.init(x: imageFrame.origin.x - errorStatusGap - ST_DTChatCell.uploadErrorBtnSize.width , y: errorY), size: ST_DTChatCell.uploadErrorBtnSize)
            }
            
            cellHeight = imageFrame.maxY + marginTop
            
        }
        
        if cellStyle == .Video{
            
            let imageWidth:CGFloat = self.videoWidth
            let imageHeight:CGFloat = self.videoHeight
            
            var displayImageWidth:CGFloat = 0
            var displayImageHeight:CGFloat = 0
                //                宽图
                if imageWidth > imageHeight{
                    
                    displayImageWidth = 140
                    
                    displayImageHeight = 140/imageWidth*imageHeight
                }
                    //                长图
                else if  imageWidth < imageHeight{
                    
                    displayImageHeight = 140
                    
                    displayImageWidth = 140/imageHeight*imageWidth
                    
                }else{
                    displayImageHeight = 140
                    displayImageWidth = 140
                }
                
                if direction == .receive{
                    
                    imageFrame = CGRect.init(origin: CGPoint.init(x: iconFrame.maxX + 10, y: iconFrame.origin.y), size: CGSize.init(width: displayImageWidth, height: displayImageHeight))
                    
                    let errorY = imageFrame.origin.y + (imageFrame.height - ST_DTChatCell.uploadErrorBtnSize.height)/2.0
                    
                    errorStatusFrame = CGRect.init(origin: CGPoint.init(x: imageFrame.maxX + errorStatusGap, y: errorY), size: ST_DTChatCell.uploadErrorBtnSize)
                    
                }else{
                    
                    imageFrame = CGRect.init(x:  iconFrame.origin.x - marginRight - displayImageWidth, y: iconFrame.origin.y, width: displayImageWidth, height: displayImageHeight)
                    
                    let errorY = imageFrame.origin.y + (imageFrame.height - ST_DTChatCell.uploadErrorBtnSize.height)/2.0
                    
                    errorStatusFrame = CGRect.init(origin: CGPoint.init(x: imageFrame.origin.x - errorStatusGap - ST_DTChatCell.uploadErrorBtnSize.width , y: errorY), size: ST_DTChatCell.uploadErrorBtnSize)
                }
                
                cellHeight = imageFrame.maxY + marginTop
            
        }
        
//        新旧礼物
        if [ST_DTChatCellStyle.goodsType,ST_DTChatCellStyle.likeProp,ST_DTChatCellStyle.incomeGuard,ST_DTChatCellStyle.incomeGift].contains(cellStyle){
            cellHeight = ST_DTChatGoodsCell.height
        }
        
        if cellStyle == .CustomNewEmoji{
            
            cellHeight = ST_DTChatEmojiCell.height
            
            if self.tail.status != .hidden{
                cellHeight += 17+5
            }
        }
        
        if cellStyle == .snapChat{
            
            cellHeight = 140+15
            
            if self.tail.status != .hidden{
                cellHeight += 17+5
            }
            
        }
        
        if cellStyle == .redPacket{
            
            cellHeight = 150+15
        }
        
        if cellStyle == .redPacketReceived{
            
            cellHeight = 17+15
        }
        
        
        if cellStyle == .tips{
            
            cellHeight = 56+10
        }
        if cellStyle == .unlockCallTips{
            cellHeight = 15+44+15+15+self.littleLuckTips.height(withConstrainedWidth: ScreenWidth - 50)
        }
        
        if cellStyle == .callRecord{
            cellHeight = 15+40
        }
        
        if cellStyle == .inviteVoiceGroup{
            
            cellHeight = 170+15
        }
        if cellStyle == .femaleInviteChat{
            
            cellHeight = 40+15
        }
    }
    
    
    /**
     检查 并且 创建 消息远程 Ext
     */
    func check_send_with_create_remote_ext(send_requre_coin:Float,source:String = "0")->Bool{
        
        var result = false
        var map = ["source":source] as [String:Any]
        
//        step 0: 是好友
        let exist = ST_BTUserInfoManager.shared.sweetheart_list?.contains(where: {$0.accid == self.chatID})
        
        if exist == true {
            result =  true
            map.updateValue(-1023, forKey: "income")
        }
        
//        step 1: 自己是女 直接发送
        else if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .female{
            map.updateValue(0, forKey: "income")
            result =  true
        }
//        step 2: 需要扣费的消息类型
        else if ST_DTChatCellStyle.ingredients.contains(self.cellStyle) == false {
            result =  true
        }
//        step 3: 设置价格为0
        else if send_requre_coin < 1 {
            
            map.updateValue(0, forKey: "income")
            
            result =  true
            
        }
        //        step 4: 按照设置价格扣费，没有伴心币 扣免费消息次数
        else if let consume = ST_BTUserInfoManager.shared.send_tnstant_message(consumeCoin: send_requre_coin) {
//         consume == 1 扣伴心币，其他扣免费消息条数
            if consume == 1{
                map.updateValue(send_requre_coin/10.0, forKey: "income")
            }else{
                
                map.updateValue(-67, forKey: "income")
                
                let number = ST_BTUserInfoManager.shared.current_account_info?.userinfo?.freeTalkCount ?? 0
                
                map.updateValue(number, forKey: "freeMsgNum")
                
            }
            result =  true
        }
        
        
//        是礼物类消息 设置 income
        if [ST_DTChatCellStyle.incomeGift,ST_DTChatCellStyle.incomeGuard].contains(self.cellStyle) {
            map.updateValue(self.goods?.income ?? 0, forKey: "income")
            
            if let num = self.goods?.giftNumber{
                map.updateValue(num, forKey: "giftNum")
            }
            
        }
        
        self.remoteExt = map
        
        return result
    }
    
        
    struct ST_ChatMessageUserInfo {
        var userId:String
        var nickName:String
        var headPic:String
    }
    
//    MARK: - 解析
    
    
    
    static func analysis(message:NIMMessage) -> ST_DTChatMessage?{
        
        
        guard let session = message.session else { return nil }
        //        往外发 userInfo是自己
        let id = message.isOutgoingMsg ? Defaults[.currentUserID] : session.sessionId
        
        guard let userInfo = ST_DTChatMessage.fetch_user_info(sessionId: id) else{
            return nil
        }
        
        let model = ST_DTChatMessage()
        
        model.uploadStatus = .success
//        往外发 并且失败
        if message.deliveryState == .failed && message.isOutgoingMsg{
            model.uploadStatus = .failure
        }
        
        model.chatID = session.sessionId
        
        model.uuid = message.messageId
        
        model.messageTime = Int64(message.timestamp)
        
//        model.messageTime = model.messageTime/1000
        
        model.direction = message.isOutgoingMsg ? .send : .receive
        
        
        model.userName = userInfo.nickName
        
        model.portraitUri = userInfo.headPic
        
        if let localExt = message.localExt  {
            
            let localJson = JSON.init(localExt)
            
            model.isSnapDestroy = localJson["isSnapDestroy"].boolValue
            
            model.passedCheck = localJson["passedCheck"].bool
        }
        
        if model.direction == .receive{
            
            if let ext = message.remoteExt{
                
                let json = JSON.init(ext)
                
                let income = json["income"].floatValue
                
                if let giftNumber = json["giftNum"].int,giftNumber > 1,let smallFont = UIFont.init(name: "Gotham", size: 20),let midFont = UIFont.init(name: "Gotham", size: 24) {
                    
                    let str = "x ".withAttributes([.font(smallFont),.textColor(#colorLiteral(red: 0.9960784314, green: 0.7607843137, blue: 0.02745098039, alpha: 1))])
                    
                    str.append(giftNumber.string.withAttributes([.font(midFont),.textColor(#colorLiteral(red: 0.9960784314, green: 0.7607843137, blue: 0.02745098039, alpha: 1))]))
                    
                    model.giftNumberAttributeString = str
                    
                }
                
                var freeMsgNum = json["freeMsgNum"].int
                
                var freeSayHiNum = json["freeSayHiNum"].int
                
//                有收益不显示 free 字段的值
                if income > 0 {
                    freeMsgNum = nil
                    freeSayHiNum = nil
                }
                
                var isReplied = false
                
                if Defaults[.repliedGoodsSet].contains(message.messageId){
                    isReplied = true
                }
                
                model.tail = ST_ChatMessageTailControlModel.init(income: income, sendDate: message.timestamp, replied: isReplied, freeMsgNum: freeMsgNum, freeSayHiNum: freeSayHiNum)
          
            }
        }
        
        
//        文字类消息
        
        
        if message.messageType == .text,let content = message.text {
            
            model.cellStyle = .Text
            
            model.chatText = content
        
        }else if let voiceModel = message.messageObject as? NIMAudioObject{
            
            model.cellStyle = .voice
//            暂时定义为远程路径
            model.voiceRemoteUrl = voiceModel.url
//            本地路径
            model.voiceLocalPath = voiceModel.path
            
            model.voiceDuration = voiceModel.duration/1000
            
        }else if let imageModel = message.messageObject as? NIMImageObject{
                    
            model.cellStyle = .Image
            
            model.thumbnailImageLocalPath = imageModel.thumbPath
            
            model.thumbnailImageRemoteUrl = imageModel.thumbUrl
            
            model.imageLocalURL = imageModel.path
            
            model.imageRemoteUrl = imageModel.url
            
            model.chatImageSize = imageModel.size
            
            if let ext = message.remoteExt{
                
                let json = JSON.init(ext)
                //等于 1 是 点赞消息
                model.displayThumbUp = json["thumbUp"].stringValue == "1"
                
                if json["snapChat"].stringValue == "true" {
                    
                    model.cellStyle = .snapChat
                    
                }
            }
            
        }else if let videoModel = message.messageObject as? NIMVideoObject{
                    
            model.cellStyle = .Video
            
//            本地
            model.videoLocalPath = videoModel.path ?? ""
            
            model.videoThumbnailPath = videoModel.coverPath ?? ""
//
//            远程
            model.videoThumbnailImageUrl = videoModel.coverUrl ?? ""
            
            model.videoUrl = videoModel.url ?? ""
            
            model.videoWidth = videoModel.coverSize.width
            
            model.videoHeight = videoModel.coverSize.height
                            
        }
//        自定义消息
        else if let customModel = message.messageObject as? NIMCustomObject {
            
            if let femaleInviteChat = customModel.attachment as? ST_BTFemaleInviteChatMessageModel{
                
                model.cellStyle = .femaleInviteChat
                
                model.femaleInviteChatType = femaleInviteChat.inviteType
                
            }else if let inviteModel = customModel.attachment as? ST_BTIMInviteMessageModel{
                
                model.cellStyle = .inviteVoiceGroup
                
                model.inviteVoiceRoom = inviteModel
                
            }else if let giftModel = customModel.attachment as? ST_BTIMGiftMessageModel{
                
                model.cellStyle = .goodsType
                
                model.goods = giftModel
                
            }else if let emojiModel = customModel.attachment as? ST_BTIMEmojiMessageModel{
                
                model.cellStyle = .CustomNewEmoji
                
                model.emoji = emojiModel
                
            }else if let cModel = customModel.attachment as? ST_Custom255AttachmentModel{
                
                model.customAttachment255 = cModel
                
                switch cModel.type {
                case 1:
                    
                    model.cellStyle = .Text
                    
                    model.chatText = "不支持的消息类型，请更新最新版后查看"
                    
//                    model.cellStyle = .redPacketReceived
//
//                    let realm = try! Realm()
//
//                    let updateModel = ST_BTRedPacketTemporaryStatusModel()
//                    updateModel.redPacketId = cModel.redPacketId
//                    updateModel.status = 1
//
//                    try! realm.write({
//                        realm.add(updateModel, update: Realm.UpdatePolicy.all)
//                    })
                    
                case 2:
                    
                    model.cellStyle = .likeProp
//                    假装 收到火箭
                    model.direction = .receive
                    
//                    获取对方头像
                    guard let targetUserInfo = ST_DTChatMessage.fetch_user_info(sessionId: session.sessionId) else{
                        return nil
                    }
                    
                    model.userName = targetUserInfo.nickName
                    
                    model.portraitUri = targetUserInfo.headPic
                    
                    let gift = ST_BTIMGiftMessageModel()
                    
                    gift.goodsId = cModel.goodsId
                    gift.title = cModel.title
                    gift.subTitle = cModel.subTitle
                    gift.imageUrl = cModel.imageUrl
                    if let url = cModel.svgaUrl,url.count > 2{
                        gift.svgaUrl = url
                        ST_GiftAssetProvider.checkoutSVGAFile(url: url)
                    }
                    model.goods = gift
                case 3:
                    model.cellStyle = .incomeGuard
                    
                    let gift = ST_BTIMGiftMessageModel()
                    
                    gift.goodsId = cModel.goodsId
                    gift.title = cModel.title
                    gift.subTitle = cModel.subTitle
                    gift.imageUrl = cModel.imageUrl
                    gift.type = .sweetGuard
                    if let url = cModel.svgaUrl,url.count > 2{
                        gift.svgaUrl = url
                        ST_GiftAssetProvider.checkoutSVGAFile(url: url)
                    }
                    model.goods = gift
                case 4,5:
                    model.cellStyle = .incomeGift
                    
                    let gift = ST_BTIMGiftMessageModel()
                    
                    gift.goodsId = cModel.goodsId
                    gift.title = cModel.title
                    gift.subTitle = cModel.subTitle
                    gift.imageUrl = cModel.imageUrl
                    if let url = cModel.svgaUrl,url.count > 2{
                        gift.svgaUrl = url
                        ST_GiftAssetProvider.checkoutSVGAFile(url: url)
                    }
               
                    model.goods = gift
                    
                default:
                    model.cellStyle = .redPacket
                    
                    let realm = try! Realm()
                    
                    
                    let localModel = realm.objects(ST_BTRedPacketTemporaryStatusModel.self).filter(NSPredicate.init(format: "redPacketId == %@", cModel.redPacketId)).first
                    
                    if let localM = localModel,let rpStaturs = ST_DTChatRedPacketStatus.init(rawValue: localM.status){
                        
                        model.redPacketStatus = rpStaturs
                        
                    }
                    
                    if model.redPacketStatus == .normal{
                        
                        if Date().hoursSince(Date.init(unixTimestamp: message.timestamp)).abs > 24{
                        
//                        if Date().minutesSince(Date.init(unixTimestamp: message.timestamp)).abs > 1{
                            
                            model.redPacketStatus = .expire
                            
                            let updateModel = ST_BTRedPacketTemporaryStatusModel()
                            updateModel.redPacketId = cModel.redPacketId
                            updateModel.status = 2
                            
                            try! realm.write({
                                realm.add(updateModel, update: Realm.UpdatePolicy.all)
                            })
                        }
                    }
                }
                
            }
            
            else if let wModel = customModel.attachment as? ST_Custom2649AttachmentModel{
                
                
//                    假装 收到微信号
                model.cellStyle = .Text

                model.direction = .receive
                
                guard let targetUserInfo = ST_DTChatMessage.fetch_user_info(sessionId: session.sessionId) else{
                    return nil
                }
                
                model.userName = targetUserInfo.nickName
                
                model.portraitUri = targetUserInfo.headPic
                
                model.chatText = wModel.wechatText
                
            }
            
            else if let wModel = customModel.attachment as? ST_Custom264AttachmentModel{
                
                model.cellStyle = .tips
                
                if model.direction == .receive{
                    model.chatText = "对方发送的消息存在风险内容，请文明聊天，共同构建和谐氛围"
                }else{
                    model.chatText = "你发送的消息存在违规信息，请文明聊天，共同构建和谐氛围"
                }
            }
            
            else if let wModel = customModel.attachment as? ST_Tian270AttachmentModel{
                
                if model.direction == .receive && wModel.type == .normalChat{
                    return nil
                }
                
                model.cellStyle = .callRecord
                
                model.callRecord = wModel
                
            }
            
            else{
                
                model.cellStyle = .Text
                
                model.chatText = "不支持的消息类型，请更新最新版后查看"
            }
            
        }else{
            
            model.cellStyle = .Text
            
            model.chatText = "不支持的消息类型，请更新最新版后查看"
        }
        
        model.figureFrame()
        
        return model
        
    }
    
    
    fileprivate class func fetch_user_info(sessionId:String)->ST_ChatMessageUserInfo?{
        
        if Defaults[.currentUserID]  == sessionId{
            
            guard let user = ST_BTUserInfoManager.shared.current_account_info?.userinfo else{
                return nil
            }
            
            return ST_ChatMessageUserInfo.init(userId: user.accid, nickName: user.nickname, headPic: user.avatar)
        }else{
            
//            sessionId是别人的ID
                var avatarUrl = ""
                var nickName = ""
//                优先显示后台返回的头像 昵称
                if let info = BINP.fetch_nickname_with_avatar(userId: sessionId){
                    avatarUrl = info.avatar
                    nickName = info.userName
                }else{
//                再查询网易云的头像
                    if let nimUser = NIMSDK.shared().userManager.userInfo(sessionId),let minUserInfo = nimUser.userInfo {
                        if let aUrl = minUserInfo.avatarUrl{
                            avatarUrl = aUrl.ni_m_url()
                        }
                        nickName = minUserInfo.nickName ?? ""
                    }else{
                        print("网易云获取用户信息失败 analysis(message） !!! ---",sessionId)
                    }
                }
            
                return ST_ChatMessageUserInfo.init(userId: sessionId, nickName: nickName, headPic: avatarUrl)
            
            
        }
        
    }
    
}





class ST_BTRedPacketTemporaryStatusModel: Object {
    
    @objc dynamic var redPacketId = ""

    @objc dynamic var status = 0
    
    override static func primaryKey() -> String? {
        return "redPacketId"
    }
}
